<!--
* description: 备件奖励单制作
* author: xiaochengzuan
* createdDate: 2021-1-21
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
      :callback-obj="callBackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import {exportExcel} from '@/utils/exportExcel';

export default {
  name: 'ProductionofSparePartsRewardList',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      selectData: [],
      callBackObj: {
        onCheckSelectChange: (sel) => {
          this.selectData = sel
        }
      },
      editRowData: {},
      // 网格查询API配置对象
      apiConfig: {
        APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusOrderMakePage.do'
      },

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'left'
        },
        {
          compKey: 'comKey3',
          type: '',
          size: 'small',
          name: 'submissionUp',
          position: 'left',
          clickEvent: () => {
            this.dataMutationByType('submit')
            // 提交
          },
          text: '提交',
          disabled: false
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => {
            this.dataMutationByType()
          },
          text: '作废',
          name: '',
          position: 'left'
        //   fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'export',
          position: 'left',
          clickEvent: () => this.export(), // 导出
          text: '导出'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => this.importTemplate(),
          text: '导入模板下载',
          position: 'left'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: '',
          text: '导入',
          position: 'upload' // 导入
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '奖励单号：',
              codeField: 'bonusOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '奖励种类: ',
              codeField: 'bonusTypeId',
              textField: 'bonusTypeName',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                listQuery: { },
                api: {
                  APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusTypes.do',
                  ServiceCode: 'queryBonusTypes'
                },
                selectType: '1'
              },
              oFields: 'bonusTypeId,bonusTypeName',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey4',
              labelName: '奖励项目：',
              codeField: 'bonusItemId',
              textField: 'bonusItemName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'bonusItemId,bonusItemName',
              customObj: {
                listQuery: { },
                api: {
                  APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusItems.do',
                },
                selectType: '1'
              },
              type: 'dropdownList',
              // isMul: true,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey4',
              labelName: '奖励金额：',
              codeField: 'bonusAmount',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey5',
              labelName: '审核状态：',
              codeField: 'bonusStatus',
              textField: 'bonusStatusCn',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                listQuery: { },
                api: { APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusStatus.do' },
                selectType: '1'
              },
              type: 'dropdownList',
              // isMul: true,
              isMust: false,
              span: 6
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '操作',
              fixed: true,
              width: 60,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => {
                    this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
                    this.showEdit('edit')
                  }
                }
              ]
            },
            {
              prop: 'dlrCode',
              label: '网点编码',
              hidden: false
            //   alwaysHidden: true
            },
            {
              prop: 'dlrShortName',
              label: '网点名称',
              width: 180
            },
            {
              prop: 'bonusOrderCode',
              label: '奖励单号'
            },
            {
              prop: 'bonusTypeName',
              label: '奖励种类'
            },
            {
              prop: 'bonusItemName',
              label: '奖励项目'
            },
            {
              prop: 'bonusAmount',
              label: '奖励金额'
            },
            {
              prop: 'creator',
              label: '创建人'
            },
            {
              prop: 'createdDate',
              label: '创建时间'
            },
            {
              prop: 'bonusStatusCn',
              label: '审核状态'
            },
            {
              prop: 'biReviewOpinions',
              label: '业务审核意见'
            },
            {
              prop: 'fiReviewOpinions',
              label: '财务审核意见'
            }

          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        bonusOrderCode: '',
        dlrShortName: '',
        bonusTypeId: '',
        bonusTypeName: '',
        bonusItemId: '',
        bonusItemName: '',
        bonusAmount: '',
        bonusStatusCn: '',
        bonusStatus: ''
        // isEnable1: '',
        // bigAreaId: '',
        // updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
    this.$refs['multipleTable'].list = [
      { releaseId: '1', updateControlId: '1' }
    ]
  },

  methods: {
    // importExcel() {
    //
    // },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message('文件大小不能超过50M')
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message('只能导入后缀为xls,xlsx的文件！')
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      const that = this
      const url = '/mp/e3sh/spareparts/finance/bonusOrderMakeService/uploadBonusOrderMakeFile.do'
      that
        .$requestUpload(url, param)
        .then(response => {
          if (response['result'] === '1') {
            this.$message({ message: '导入成功', type: 'success' })
            that.queryTable()
          } else {
            this.$message({ message: response['msg'], type: 'warning' })
          }
        })
        .catch(err => { console.log(err) })
        .finally(() => {
          loading.close()
        })
    },
    importTemplate() {
      const loading = this.$loading({
        text: '正在下载Excel模板...',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      this.$requestAPI({
        // method: 'GET',
        variables: { dataType: 'excel' },
        apiUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/downBonusOrderMakeTemplateFile.do'
      }).then(res => {
        this.$utils.downloadFile(res, '备件奖励单模板.xlsx')
      }).catch(err => {
        this.$message('下载出错!')
        console.log(err)
      }).finally(() => {
        loading.close()
      })
    },
    dataMutationByType(type) {
      this.$confirm('确定要提交吗?', '提示', {
        type: 'warning'
      }).then(() => {
        // 提交和作废 api
        const apiUrl = type === 'submit'
          ? '/mp/e3sh/spareparts/finance/bonusOrderMakeService/editBonusOrderMakeSubmitStatus.do'
          : '/mp/e3sh/spareparts/finance/bonusOrderMakeService/editBonusOrderMakeinvalidStatus.do'
        this.$requestAPI({
          apiUrl,
          variables: {
            bonusOrderStatus: this.selectData.reduce((pre, cur, idx) => {
              const { bonusOrderId, updateControlId } = cur
              pre.push({ bonusOrderId, updateControlId })
              return pre
            }, [])
          }
        }).then(response => {
          if (response.result === '1') {
            this.queryTable()
            this.$message(type === 'submit' ? '提交成功!' : '作废成功')
          } else {
            this.$message(response.msg)
          }
        }).catch(err => {
          // loading.close()
          if (err.response.data.msg) {
            this.$message(err.response.data.msg)
          } else {
            this.$message(err.message)
          }
        })

      })

    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
    },

    // 导出
    export() {
      exportExcel.call(this, '/mp/e3sh/spareparts/finance/bonusOrderMakeService/exportBonusOrderMake.do')
    }
  }
}
</script>
